package com.henry.imkit.request

import com.blankj.utilcode.util.StringUtils
import com.henry.imkit.*
import com.henry.imkit.ErrorCode.UPLOAD_FAILED
import com.henry.imkit.IMKit
import com.henry.imkit.models.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File

object IMRequest {

    /**
     * 完整的URL(包含http)
     */
    fun getCompleteUrl(url: String): String {
        val imDomain = IMKit.instance.domain

        if (StringUtils.isEmpty(url)) return ""
        if (url.contains("http://") || url.contains("https://")) {
            return url
        }
        return if (url.startsWith("/")) {
            imDomain + url
        } else "$imDomain/$url"
    }

    /**
     * sessionId
     */
    fun imSessionId(
            onSuccess: ((data: String) -> Unit)? = null,
            onError: OnErrorCallback? = null) {
        IMRetrofit.service.imSessionId().ssss({
            if (it.status) {
                onSuccess?.invoke(it.sessionid ?: "")
            } else {
                onError?.invoke(it.informationcode, it.msg)
            }
        }, onError)
    }

    /**
     * 连接websocket前请求
     */
    fun websocket(
            onSuccess: ((data: String) -> Unit)? = null,
            onError: OnErrorCallback? = null) {
        IMRetrofit.service.websocket().ssss({
            onSuccess?.invoke(it)
        }, onError)
    }

    /**
     * 用户信息
     */
    fun userInfo(
        userId: String,
        onSuccess: ((data: String) -> Unit)? = null,
        onError: OnErrorCallback? = null,
    ) {
        IMRetrofit.service.userInfo(userId).ssss({

        }, onError)
    }

    /**
     * 会话列表
     */
    fun getConversations(
        type: String, page: Int, size: Int,
        onSuccess: ((data: List<ConversationData>, t: Int) -> Unit)? = null,
        onError: OnErrorCallback? = null,
    ) {

        val body = ConversationBody(type, page, size)
        IMRetrofit.service.getConversations(body).ssss({
            if (it.status) {
                onSuccess?.invoke(it.list, it.total)
            } else {
                onError?.invoke(it.informationcode?:ErrorCode.SERVER_ERROR, it.msg.toString())
            }
        }, onError)
    }

    /**
     * 会话信息
     */
    fun getConversationInfo(
        cgid: String,
        onSuccess: ((data: ConversationInfoRepo) -> Unit)? = null,
        onError: OnErrorCallback? = null
    ) {
        val body = ConversationInfoBody(cgid)
        IMRetrofit.service.getConversationInfo(body).ssss({
            onSuccess?.invoke(it)
        }, onError)
    }

    /**
     * 创建会话
     */
    fun createConversation(
        name: String, type: String, users: String, dgid: String, sessionId: String,
        onSuccess: ((data: ConversationData) -> Unit)? = null,
        onError: OnErrorCallback? = null
    ) {
        val info = CreateConversationInfoBody(type, name, dgid)
        val body = CreateConversationBody(users, info, sessionId)
        IMRetrofit.service.createConversation(body).ssss({
            if (it.status) {
                onSuccess?.invoke(it.discussgroup!!)
            } else {
                onError?.invoke(it.informationcode, it.msg)
            }
        }, onError)
    }

    /**
     * 更新会话
     */
    fun updateConversation(
        dgid: String, name: String,
        onSuccess: ((data: BaseRepo) -> Unit)? = null,
        onError: OnErrorCallback? = null
    ) {
        val body = UpdateConversationBody(dgid, name)
        IMRetrofit.service.updateConversation(body).ssss({
            if (it.status) {
                onSuccess?.invoke(it)
            } else {
                onError?.invoke(it.informationcode, it.msg)
            }
        }, onError)
    }

    /**
     * 添加成员
     */
    fun addMembers(
        dgid: String, users: String,
        onSuccess: ((data: BaseRepo) -> Unit)? = null,
        onError: OnErrorCallback? = null
    ) {
        val body = AddMembersBody(dgid, users)
        IMRetrofit.service.addMembers(body).ssss({
            if (it.status) {
                onSuccess?.invoke(it)
            } else {
                onError?.invoke(it.informationcode, it.msg)
            }
        }, onError)
    }

    /**
     * 删除成员
     */
    fun deleteMembers(
        dgid: String, users: String,
        onSuccess: ((data: BaseRepo) -> Unit)? = null,
        onError: OnErrorCallback? = null
    ) {
        val body = AddMembersBody(dgid, users)
        IMRetrofit.service.deleteMembers(body).ssss({
            if (it.status) {
                onSuccess?.invoke(it)
            } else {
                onError?.invoke(it.informationcode, it.msg)
            }
        }, onError)
    }

    /**
     * 平台下用户列表
     */
    fun getUserList(
        dgid: String, keyword: String, page: Int, size: Int,
        onSuccess: ((data: List<User>) -> Unit)? = null,
        onError: OnErrorCallback? = null
    ) {
        IMRetrofit.service.getUserList(dgid, keyword, page, size).ssss({
            if (it.status) {
                onSuccess?.invoke(it.list)
            } else {
                onError?.invoke(it.informationcode?:0, it.msg.toString())
            }
        }, onError)
    }

    /**
     * 聊天记录
     */
    fun messages(
        dgid: String, time: String, size: Int,
        onSuccess: ((data: List<MessageData>) -> Unit)? = null,
        onError: OnErrorCallback? = null
    ) {
        IMRetrofit.service.messages(dgid, time, size).ssss({
            if (it.status) {
                onSuccess?.invoke(it.list)
            } else {
                onError?.invoke(it.informationcode, it.msg)
            }
        }, onError)
    }

    fun uploadChatImages(
        files: List<File>, dgid: String?,
        onSuccess: ((data: List<FileData>) -> Unit)? = null,
        onError: OnErrorCallback? = null) {

        val list = mutableListOf<MultipartBody.Part>()
        for (file in files) {
            val requestFile = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
            val part = MultipartBody.Part.createFormData("file", file.name, requestFile)
            list.add(part)
        }

        IMRetrofit.service.uploadMultipartFile("chat", dgid.toString(), list).ssss({

            if (it.status) {
                it.rows?.let { it1 -> onSuccess?.invoke(it1) }
            } else {
                onError?.invoke(UPLOAD_FAILED, it.msg)
            }
        }, onError)

    }

    fun uploadChatAudio(
            file: File, dgid: String?,
            onSuccess: ((data: String) -> Unit)? = null,
            onError: OnErrorCallback? = null) {
        val requestFile = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
        val part = MultipartBody.Part.createFormData("file", file.name, requestFile)

        IMRetrofit.service.uploadSingleFile("chat", dgid.toString(), part).ssss({
            if (it.status) {
                onSuccess?.invoke(it.url.toString())
            } else {
                onError?.invoke(UPLOAD_FAILED, it.msg)
            }
        }, onError)
    }

    fun getRTCDomain(onSuccess: ((data: String) -> Unit)? = null,
                     onError: OnErrorCallback? = null) {
        IMRetrofit.service.getRTCDomain().ssss({
            if (it.status) {
                onSuccess?.invoke(it.domain?.domain?:"")
            } else {
                onError?.invoke(it.informationcode, it.msg)
            }
        }, onError)
    }

}